import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.UUID;

public class Main {

    /**
     * 修改本地图片水印
     *
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        File url = new File("C:\\Users\\Lenovo\\Desktop\\课表.jpg");
        BufferedImage image = ImageIO.read(url);
        int width = image.getWidth();
        int height = image.getHeight();


        BufferedImage bufImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// 加水印
//创建画笔
        Graphics2D g = bufImg.createGraphics();
//srcImg 为上面获取到的原始图片的图片对象
        g.drawImage(image, 0, 0, width, height, null);
//根据图片的背景设置水印颜色
        g.setColor(new Color(86, 88, 93, 128));
//设置字体  画笔字体样式为微软雅黑，加粗，文字大小为60pt
        g.setFont(new Font("微软雅黑", Font.BOLD, 60));
//设置水印的坐标
//int x=200;
//int y=200;
        String waterMarkContent = "郑声军的水印";
        //中间
        /*
        int x = (width - getWatermarkLength(waterMarkContent, g)) / 2;
        int y = height / 2;
        */
        //右上
//        int x = width - getWatermarkLength(waterMarkContent, g);
//        int y = 60;
//        System.out.println(height);
//        int x = width - getWatermarkLength(waterMarkContent,g);
//        int y = (height -60);

//画出水印 第一个参数是水印内容，第二个参数是x轴坐标，第三个参数是y轴坐标
        //左上
//        g.drawString(waterMarkContent, x, y);
        //如果铺满的话是根据像素的各个方向来画 每一行四个 根据大小来算
        int row = width / 4; //每行画四个水印
        int column = height / 5;//一共画五行
        int rowBegin = 0;
        int columnBegin = 0;
        for (int i = 0; i < 4; i++) {
            columnBegin = 0;
            for (int j = 0; j < 5; j++) {
                g.drawString(waterMarkContent, rowBegin, columnBegin += column);
            }
            rowBegin += row;
        }
        g.dispose();
        g.dispose();
        //
        //待存储的地址
        String tarImgPath = "C:\\Users\\Lenovo\\Desktop\\t\\" + UUID.randomUUID().toString() + ".jpg";
// 输出图片
        FileOutputStream outImgStream = new FileOutputStream(tarImgPath);
        ImageIO.write(bufImg, "png", outImgStream);
        System.out.println("添加水印完成");
        outImgStream.flush();
        outImgStream.close();

    }

    /**
     * 获取水印文字的长度
     *
     * @param waterMarkContent
     * @param g
     * @return
     */
    public static int getWatermarkLength(String waterMarkContent, Graphics2D g) {
        return g.getFontMetrics(g.getFont()).charsWidth(waterMarkContent.toCharArray(), 0, waterMarkContent.length());
    }

}